package com.hand.qt24953.order.infra.repository.impl;

import com.hand.qt24953.order.domain.entity.SoLine;
import com.hand.qt24953.order.domain.repository.SoLineRepository;
import org.hzero.core.exception.MessageException;
import org.hzero.mybatis.base.impl.BaseRepositoryImpl;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 销售订单行 资源库实现
 *
 * @author tao.qiu01@hadn-china.com 2019-08-02 11:30:00
 */
@Component
public class SoLineRepositoryImpl extends BaseRepositoryImpl<SoLine> implements SoLineRepository {

    @Override
    public int insertSelective(SoLine record) {
        List<SoLine> lineList = select(SoLine.FIELD_SO_HEADER_ID, record.getSoHeaderId());
        if (record.getLineNumber() != null && lineList != null && lineList.size() > 0) {
            if (lineList.stream().anyMatch(line -> line.getLineNumber().equals(record.getLineNumber()))) {
                throw new MessageException("行号重复");
            } else {
                return super.insertSelective(record);
            }
        }
        long lineNumber;
        if (lineList == null || lineList.size() < 1) {
            //行号从1开始
            lineNumber = 1L;
        } else {
            lineNumber = lineList.stream().mapToLong(SoLine::getLineNumber).max().getAsLong() + 1L;
        }

        record.setLineNumber(lineNumber);
        return super.insertSelective(record);
    }
}
